package thread;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;

/**
 * @author： hmm
 * @date： 2020/7/6 16:04
 * @description： 学习ThreadLocal
 * @modifiedBy：
 *  ThreadLocal作为共享变量，当多个线程操作时，线程间互不影响，是实现线程安全的一个手段
 */
public class ThreadLocalDemo {
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(2);

        new Thread(() -> {
            update();
            System.out.println(threadLocal.get());
            //System.out.println(threadLocal);
            countDownLatch.countDown();
        }).start();
        new Thread(()->{
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            update();
            System.out.println(threadLocal.get());
            //System.out.println(threadLocal);
            countDownLatch.countDown();
        }).start();

        countDownLatch.await();
        System.out.println("执行结束");
    }

    public static ThreadLocal<Integer> threadLocal = ThreadLocal.withInitial(() -> 0);
    //public static Integer threadLocal = 0;

    public static void update() {
        Integer i = threadLocal.get();
        System.out.println(Thread.currentThread().getName()+ ": threadLocal.get： " + i);
        i ++;
        threadLocal.set(i);
        System.out.println(Thread.currentThread().getName()+ ": threadLocal.get： " + i);
        //threadLocal++;
    }
}
